package com.leyou.item.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entitiy.TbBrand;
import com.leyou.item.entitiy.TbCategoryBrand;
import com.leyou.item.mapper.TbBrandMapper;
import com.leyou.item.service.TbBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.service.TbCategoryBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 品牌表，一个品牌下有多个商品（spu），一对多关系 服务实现类
 * </p>
 *
 * @author HM
 * @since 2021-06-16
 */
@Service
public class TbBrandServiceImpl extends ServiceImpl<TbBrandMapper, TbBrand> implements TbBrandService {
    @Autowired
    private TbCategoryBrandService categoryBrandService;

    @Override
    public PageResult<BrandDTO> searchPage(Integer page, Integer rows, String key, String sortBy,
                                           Boolean desc) {
        Page p = new Page<TbBrand>(page,rows);
        QueryWrapper<TbBrand> queryWrapper = new QueryWrapper<>();
        //条件判断，添加
        if(!StringUtils.isEmpty(key)){
            queryWrapper.lambda().like(TbBrand::getName,key).or().like(TbBrand::getLetter,key);
        }
        if(!StringUtils.isEmpty(sortBy)){
            if(desc){
                p.setDesc(sortBy);
            }else{
                p.setAsc(sortBy);
            }
        }
        IPage iPage = this.page(p, queryWrapper);
        if(iPage == null || CollectionUtils.isEmpty(iPage.getRecords())){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        List<BrandDTO> brandDTOS = BeanHelper.copyWithCollection(iPage.getRecords(), BrandDTO.class);
        return new PageResult( iPage.getTotal(), iPage.getPages(),brandDTOS);
    }

    @Override
    @Transactional
    public void saveBrandAndCategory(TbBrand brand, List<Long> cids) {
        //保存品牌表
        boolean brandB = this.save(brand);
        if(!brandB){
            throw  new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        Long brandId = brand.getId();
        if(!CollectionUtils.isEmpty(cids)){
            List list = new ArrayList<TbCategoryBrand>();
            for (Long cid : cids) {
                TbCategoryBrand tbCategoryBrand = new TbCategoryBrand();
                tbCategoryBrand.setBrandId(brandId);
                tbCategoryBrand.setCategoryId(cid);
                list.add(tbCategoryBrand);
            }
            //批量保存 分类品牌 中间表
            categoryBrandService.saveBatch(list);
        }
    }

    @Override
    @Transactional
    public void updateBrandAndCategory(TbBrand brand, List<Long> cids) {
        boolean b = this.updateById(brand);
        if(!b){
            throw  new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        Long brandId = brand.getId();
        if(!CollectionUtils.isEmpty(cids)){
            //先删除,中间表
            QueryWrapper<TbCategoryBrand> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TbCategoryBrand::getBrandId,brandId);
            boolean removeB = categoryBrandService.remove(queryWrapper);
            if(!removeB){
                throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
            }
            //新增 中间表
            List list = new ArrayList<TbCategoryBrand>();
            for (Long cid : cids) {
                TbCategoryBrand tbCategoryBrand = new TbCategoryBrand();
                tbCategoryBrand.setBrandId(brandId);
                tbCategoryBrand.setCategoryId(cid);
                list.add(tbCategoryBrand);
            }
            categoryBrandService.saveBatch(list);
        }
    }

    @Override
    public List<BrandDTO> queryByCategoryId(Long categoryId) {
        List<TbBrand> brandList = this.baseMapper.selectBrandJoinCategory(categoryId);
        if(CollectionUtils.isEmpty(brandList)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(brandList,BrandDTO.class);
    }
}
